<template>
    <div style="width:100%; height:100%;">
        <iframe id="map-container" :src="fullUrl" frameborder="0" width="100%" height="100%"/>
        <van-dialog v-model="forma.show" title="详细地址修改" show-cancel-button @confirm="eventClickSettingAddress">
            <van-field v-model="forma.address" autofocus placeholder="请输入详细的地址信息"/>
        </van-dialog>
    </div>
</template>

<script>
    import {Toast, Dialog, Field} from 'vant';

    export default {
        name: "MapSelectAddress",
        components: {
            [Dialog.Component.name]: Dialog.Component,
            [Field.name]: Field
        },
        data() {
            return {
                fullUrl: '',
                baseUrl: 'https://m.amap.com/picker/?keywords=写字楼,小区,学校&zoom=15&radius=1000&total=30',
                key: '&key=a9cee9141c7a483fe481b6d78f554f47',
                location: '&center=',
                forma: {
                    show: false,
                    address: '',
                    item: null
                }
            }
        },
        mounted() {
            this.fullUrl = this.baseUrl + this.key;
            // this.controllerEstablishIframeEventListener();

            if (this.$route.query.mode == 'edit') {
                this.location += this.$route.query.longitude + ',' + this.$route.query.latitude;
                this.fullUrl = this.baseUrl + this.location + this.key;
                this.controllerEstablishIframeEventListener();
            } else {
                this.controllerInitializationMapIframe();
            }
        },
        methods: {
            initializationLoadAmapSourceOperate() {
                return new Promise((resolve, reject) => {
                    this.$util.loadSourceUrl({
                        mode: 'script',
                        url: 'https://webapi.amap.com/maps?v=1.4.15&key=a9cee9141c7a483fe481b6d78f554f47&plugin=AMap.Geocoder',
                        name: 'gaode-map',
                        resolve: resolve,
                        reject: reject
                    });
                });
            },
            amapControllerOperate() {
                this.map.setCenter(this.longitude, this.latitude);

                var marker = new AMap.Marker({
                    position: map.getCenter(),
                    icon: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',
                    offset: new AMap.Pixel(-13, -30),
                    // 设置是否可以拖拽
                    draggable: true,
                    cursor: 'move',
                    // 设置拖拽效果
                    raiseOnDrag: true
                });

                marker.setMap(this.map);
            },
            initializationWeChatSDKEnvironment() {
                return new Promise((resovle, reject) => {
                    this.$util.requestLoadWeChatSDKOperate(['checkJsApi', 'openLocation', 'getLocation']).then(
                        this.$util.requestWeChatAuthorizeDataset
                    ).then(
                        (res) => {
                            resovle();
                        }
                    ).catch(
                        (frs) => {
                            reject(frs);
                        }
                    );
                });
            },
            requestWeChatLocationInterface() {
                return new Promise((resolve, reject) => {
                    wx.getLocation({
                        // 默认为 wgs84 的 gps 坐标，如果要返回直接给 openLocation 用的火星坐标，可传入 gcj02
                        type: 'gcj02',
                        success: (res) => {
                            // res.longitude, res.latitude
                            resolve(res);
                        },
                        cancel: function (fres) {
                            // alert('用户拒绝授权获取地理位置');
                            reject(fres);
                        }
                    });
                });
            },
            requestGetUserLocationData(res) {
                return new Promise((resolve, reject) => {
                    if (!this.geocoder) {
                        this.geocoder = new AMap.Geocoder({
                            radius: 100,
                            extensions: "all"
                        });
                    }

                    // 将当前定位的坐标转换为地址信息
                    this.geocoder.getAddress([res.longitude, res.latitude], (status, result) => {
                        if (status === 'complete' && result.info === 'OK') {
                            if (result.regeocode) {
                                // result.regeocode.formattedAddress
                                resolve({
                                    res, result
                                });
                            } else {
                                reject();
                            }
                        } else {
                            reject();
                        }
                    });
                });
            },
            controllerDemo() {
                this.initializationLoadAmapSourceOperate().then(
                    (params) => {
                        // this.map = new AMap.Map('container', {
                        //     resizeEnable: true,
                        //     zoom: 4
                        // });

                        this.initializationWeChatSDKEnvironment().then(
                            this.requestWeChatLocationInterface
                        ).then(
                            this.requestGetUserLocationData
                        ).then(
                            (gather) => {
                                var {res, result} = gather;
                                // 经纬度
                                this.longitude = res.longitude;
                                this.latitude = res.latitude;
                                // res.regeocode.formattedAddress
                                this.neighborhood = res.addressComponent.neighborhood;
                                this.formattedAddress = res.regeocode.formattedAddress;
                                // 地图控制操作
                                this.amapControllerOperate();
                            }
                        ).catch(
                            (frs) => {
                                console.log('wx-location-amap', frs);
                            }
                        );
                    }
                ).catch(
                    (frs) => {
                        console.log('mounted', frs);
                    }
                );
            },
            controllerInitializationMapIframe(res) {
                Toast.loading({
                    message: '加载中', loadingType: 'spinner', forbidClick: true, duration: 0
                });

                this.initializationWeChatSDKEnvironment().then(
                    this.requestWeChatLocationInterface
                ).then(
                    (res) => {
                        // this.fullUrl = this.baseUrl + this.key;
                        this.fullUrl = this.baseUrl + this.location + `${res.longitude},${res.latitude}` + this.key;
                        this.controllerEstablishIframeEventListener();

                        setTimeout(() => {
                            Toast.clear();
                        }, 3000);
                    }
                ).catch(
                    (frs) => {
                        // console.log(frs);
                        Toast.clear();

                        Dialog.alert({
                            title: '提示', message: '此功能需要在微信端使用'
                        }).then(() => {
                            this.$router.push('/shop/regedit');
                        });
                    }
                );
            },
            controllerEstablishIframeEventListener() {
                var iframe = document.getElementById('map-container').contentWindow;

                document.getElementById('map-container').onload = function () {
                    iframe.postMessage('hello', 'https://m.amap.com/picker/');
                    Dialog.alert({
                        title: '操作提示',
                        message: '拖动地图选择位置，然后点击下方列表修改详细地址'
                    });
                };

                window.addEventListener('message', (e) => {
                    this.forma.item = e;
                    this.forma.address = e.data.address;
                    this.forma.show = true;
                }, false);
            },
            eventClickSettingAddress() {
                if (this.$route.query.mode == 'edit') {
                    this.$router.push({
                        name: 'TemporaryDirectorEditShopInfo', params: {
                            name: this.forma.item.data.name,
                            location: this.forma.item.data.location,
                            address: this.forma.address
                        }
                    });
                } else {
                    this.$router.push({
                        name: 'ShopRegedit', params: {
                            name: this.forma.item.data.name,
                            location: this.forma.item.data.location,
                            address: this.forma.address
                        }
                    });
                }
            }
        }
    }
</script>

<style lang="scss">
    html,
    body {
        height: 100%;
    }

    .selectAddressMap {
        height: 100%;

        #container {
            height: 90%;
        }
    }
</style>
